package ua.kpi.ipsa.expert.api;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 
 * @author doctorpro
 * 
 */
public class Properties {

	public static final String DATABASE_PATH = "dbpath";
	public static final String CLASSPATH = "classpath";
	public static final String DELIMITER = "=";

	public static final String DEFAULT_PROPS_FILE = "api_props.txt";

	private File file;
	private Map<String, String> m;
	private Map<String, String> defaults;

	/**
	 * 
	 * @param file
	 * @throws IOException
	 */
	public Properties(File file) throws IOException {
		this.file = file;
		m = new HashMap<String, String>();
		defaults = new HashMap<String, String>();

		fillDefaults();

		if (this.file == null) {
			this.file = new File(DEFAULT_PROPS_FILE);
		}

		load();
	}

	/**
	 * 
	 */
	private void fillDefaults() {

		// database path
		File apiDir = new File(System.getProperty("user.home"), ".api");
		File dbFile = new File(apiDir, "krutayadb");
		File classpathDir = new File(apiDir, "classes");
		defaults.put(DATABASE_PATH, dbFile.getAbsolutePath());
		defaults.put(CLASSPATH, classpathDir.getAbsolutePath());
	}

	/**
	 * 
	 */
	public Properties() throws IOException {
		this(null);
	}

	public String get(String k) {
		return m.get(k);
	}

	public void put(String k, String v) {
		if ((k == null) || (v == null)) {
			throw new NullPointerException();
		}
		m.put(k, v);
	}

	/**
	 * 
	 * @throws IOException
	 */
	public void store() throws IOException {

		PrintWriter out = new PrintWriter(file);

		for (Iterator<String> i = m.keySet().iterator(); i.hasNext();) {
			String k = i.next();
			out.println(k + DELIMITER + m.get(k));
		}

		out.flush();
		out.close();
	}

	/**
	 * 
	 */
	@Override
	public void finalize() {
		try {
			store();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 
	 */
	private void load() throws IOException {

		if (file.exists()) {
			BufferedReader in = new BufferedReader(new FileReader(file));
			String line = in.readLine();
			while (line != null) {
				String[] ar = line.split(DELIMITER, 2);
				m.put(ar[0], ar[1]);
				line = in.readLine();
			}
			in.close();
		}
		assertLoaded();
		
		if (!file.exists()) {
			store();
		}
	}

	/**
	 * 
	 */
	private void assertLoaded() {

		for (Iterator<String> i = defaults.keySet().iterator(); i.hasNext();) {
			String k = i.next();
			if (!m.containsKey(k)) {
				m.put(k, defaults.get(k));
			}
		}
	}
}
